package dao.impl;

import dao.BaseDao;
import dao.StudentLoginDao;
import entity.Student;

import java.sql.*;

public class StudentLoginDaoImpl extends BaseDao implements StudentLoginDao {

    @Override
    public Student Login(String username, String password, String role)
            throws SQLException, ClassNotFoundException {
      getConnection();
        PreparedStatement pst = null;
        ResultSet rs = null;

        try {

            String sql = "SELECT user_id, username, password, role, sex, phone, created_at, facePhoto " +
                    "FROM users WHERE username = ? AND password = ? AND role = ?";
            pst = conn.prepareStatement(sql);
            pst.setString(1, username);
            pst.setString(2, password);
            pst.setString(3, role);

            rs = pst.executeQuery();

            if (rs.next()) {
                Student student = new Student();
                student.setUser_id(rs.getString("user_id"));
                student.setUsername(rs.getString("username"));
                student.setPassword(rs.getString("password"));
                student.setRole(rs.getString("role"));
                student.setSex(rs.getString("sex"));
                student.setPhone(rs.getString("phone"));
                student.setCreated_at(rs.getString("created_at"));
                student.setFacePhoto(rs.getString("facePhoto"));
                return student;
            }
            return null;
        } finally {
            // 确保资源被关闭，关闭顺序与打开顺序相反
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    System.err.println("关闭ResultSet失败: " + e.getMessage());
                }
            }
            if (pst != null) {
                try {
                    pst.close();
                } catch (SQLException e) {
                    System.err.println("关闭PreparedStatement失败: " + e.getMessage());
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    System.err.println("关闭Connection失败: " + e.getMessage());
                }
            }
        }
    }
}